import type { UserConfig } from 'vite'
import path from 'node:path'
import { defineConfig, loadEnv } from 'vite'
import { createVitePlugins } from './build/plugins'
import { createViteProxy } from './build/proxy'

// https://vitejs.dev/config/
export default defineConfig(async ({ command, mode }): Promise<UserConfig> => {
  console.log('command, mode -> ', command, mode)
  const env = loadEnv(mode, process.cwd())
  console.log('env -> ', env)
  const { UNI_PLATFORM } = process.env
  console.log('UNI_PLATFORM -> ', UNI_PLATFORM)

  return {
    plugins: [
      ...await createVitePlugins(env),
    ],
    define: {
      __UNI_PLATFORM__: JSON.stringify(UNI_PLATFORM),
    },
    resolve: {
      alias: {
        '@': path.join(process.cwd(), './src'),
      },
    },
    optimizeDeps: {
      exclude: ['sard-uniapp'],
    },
    server: {
      host: '0.0.0.0',
      port: 9527,
      hmr: true,
      proxy: UNI_PLATFORM === 'h5' ? createViteProxy(env) : undefined,
    },
    build: {
      sourcemap: true,
      target: 'es6',
      minify: mode === 'development' ? false : 'terser',
      terserOptions: {
        compress: {
          drop_console: env.VITE_DROP_CONSOLE === 'true',
          drop_debugger: true,
        },
      },
    },
  }
})
